package com.project.myPackage.controller;

import com.project.myPackage.utils.ZxingUtil;
import io.swagger.annotations.Api;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

@Api(tags = "二维码管理")
@RestController
@RequestMapping("/")
public class QrcodeController {

    /**
     * 生成二维码
     * post x-www-form-urlencoded  text | http://baidu.com
     * @param text url地址
     * @return 二维码图片
     */
    @PostMapping(value = "/qrcode")
    public ResponseEntity<byte[]> createQrcode(
            @RequestBody String text
    ) {

        try {
            // 去除 "text=" 前缀
            String encodedText = text.substring("text=".length());

            // URL 解码
            String decodedText = URLDecoder.decode(encodedText, StandardCharsets.UTF_8.toString());

            // 生成二维码图像
            BufferedImage image = ZxingUtil.createImage(decodedText);

            // 将 BufferedImage 转换为字节数组
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(image, "png", os);
            byte[] imageBytes = os.toByteArray();

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_PNG);
            headers.setContentDispositionFormData("inline", "qrcode.png");

            return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


}
